package servlet.wxpay;

import pojo.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import servlet.wxpay.sdk.MyConfig;
import servlet.wxpay.sdk.WXPay;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/WxPayServlet",name = "WxPayServlet")
public class WxPayServlet extends HttpServlet {

    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String orderNO = request.getParameter("orderNO");
        Order order = orderService.findByOrderNO(orderNO);
        try {

            MyConfig config = new MyConfig();
            WXPay wxpay = new WXPay(config);

            Map<String, String> data = new HashMap<String, String>();
            data.put("body", order.getBody());
            data.put("out_trade_no", order.getOrderNO());
            data.put("device_info", "WEB");
            data.put("fee_type", "CNY");
            int total_fee = (int)(order.getAmount()*100);
            data.put("total_fee", total_fee+"");
            data.put("spbill_create_ip", getRemortIP(request));
            data.put("notify_url", config.getNotifyUrl());
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
            data.put("product_id", "1");

            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);

            if (resp.get("return_code").equals("SUCCESS") && resp.get("result_code").equals("SUCCESS")){
                request.setAttribute("code_url", resp.get("code_url"));
                request.setAttribute("orderNO", order.getOrderNO());
                request.getRequestDispatcher("showQRCode.jsp").forward(request, response);
            } else {
                out.print(resp.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户IP
     * @param request
     * @return
     */
    private String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");

    }

}
